package com.sbm.quartz;

import java.text.SimpleDateFormat;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 实现CommandLineRunner接口
 * SpringBoot启动后自动运行
 * 可通过设置@Order(value=1)来控制运行顺序
 * 加载任务并启动触发
 * @author Administrator
 */
@Component
public class QuartzJobLoader implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzJobLoader.class);

    @Autowired
    private QuartzConfig config;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private TaskLoader loader;

    @Override
    public void run(String... args) throws Exception {
        if(!this.config.isLoadJobs()){
            LOGGER.info("Quartz：设置了不加载任务");
            return;
        }
        LOGGER.info("Quartz：————装载任务开始————");
        List<TaskInfo> tasks = this.loader.getTasks();
        for (TaskInfo task : tasks) {
            ScheduleJob(task);
        }
        LOGGER.info("Quartz：————装载任务完成————");
    }

    public boolean ScheduleJob(TaskInfo task)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        try {
            LOGGER.info("Quartz：加载任务[" + task.getGroup() + "." + task.getName() + "]");
            if (task.getStartTime() != null)
                LOGGER.info("Quartz：启动时间[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getStartTime()) + "]");
            if (task.getEndTime() != null)
                LOGGER.info("Quartz：结束时间[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getEndTime()) + "]");
            if(!task.isRunnable()){
                LOGGER.info("Quartz：任务不运行");
                return true;
            }
            @SuppressWarnings("unchecked")
            Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(task.getClazz()).newInstance()
                    .getClass();
            // 构建Job
            JobBuilder jobBuilder = JobBuilder.newJob(jobClass);
            jobBuilder.withIdentity(task.getName(), task.getGroup());
            jobBuilder.withDescription(task.getDescription());
            JobDetail jobDetail = jobBuilder.build();
            jobDetail.getJobDataMap().putAll(task.getData());
            // 构建表达式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCron());
            scheduleBuilder.withMisfireHandlingInstructionDoNothing();
            // 构建触发器
            TriggerBuilder<CronTrigger> triggerBuilder = TriggerBuilder.newTrigger().withIdentity(task.getId())
                    .withSchedule(scheduleBuilder);
            if (task.getStartTime() != null)
                triggerBuilder.startAt(task.getStartTime());
            if (task.getEndTime() != null)
                triggerBuilder.endAt(task.getEndTime());
            CronTrigger trigger = triggerBuilder.build();
            // 添加到管理
            scheduler.scheduleJob(jobDetail, trigger);
            LOGGER.info("Quartz：加载成功");
            return true;
        } catch (SchedulerException ex) {
            LOGGER.error("Quartz：加载失败--" + ex.getMessage());
            return false;
        }
    }
}
